<template>
  <div class="container">
    <div v-loading="isLoadingOfList" class="app-container">
      <el-tree default-expand-all :data="list" :props="treeProps">
        <!-- slot 旧版语法 兼容性强 -->
        <template slot="default" slot-scope="{ data }">
          <!-- 填充的每个节点的自定义结构，作为默认插槽插入到 el-tree 组件内部，组件内部会对其进行遍历循环渲染 -->
          <!-- el-row 一行 24份 -->
          <el-row style="width: 100%;">
            <!-- 用 span 属性指向该列占多少行 -->
            <el-col :span="20">{{ data.name }}</el-col>
            <el-col :span="4">
              <el-row>
                <el-col :span="8">{{ data.managerName }}</el-col>
                <el-col :span="16">
                  <!-- .native 监听的事件最终会绑定在 组件的根元素 上 -->
                  <el-dropdown trigger="click" @click.native.stop @command="handleCommand($event, data)">
                    <span slot="default">
                      操作<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                      <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                      <el-dropdown-item command="del">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 添加子部门 -->
    <el-dialog :title="addDeptDialog.title" :visible.sync="addDeptDialog.visible">
      <el-form ref="refAddDeptForm" :model="addDeptDialog.form.data" :rules="addDeptDialog.form.rules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input ref="refAddDeptFormOfName" v-model="addDeptDialog.form.data.name" style="width: 90%;" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input ref="refAddDeptFormOfCode" v-model="addDeptDialog.form.data.code" style="width: 90%;" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="addDeptDialog.form.data.managerId" style="width: 90%;" @visible-change="addDeptDialog.methods.onVisibleChangeOfManager">
            <el-option
              v-for="v of addDeptDialog.ManagerList"
              :key="v.id"
              :label="v.username"
              :value="v.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="addDeptDialog.form.data.introduce" style="width: 90%;" type="textarea" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addDeptDialog.methods.ok">确定</el-button>
          <el-button @click="addDeptDialog.visible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑部门 -->
    <el-dialog :title="editDeptDialog.title" :visible.sync="editDeptDialog.visible">
      <el-form ref="refEditDeptForm" :model="editDeptDialog.form.data" :rules="editDeptDialog.form.rules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editDeptDialog.form.data.name" style="width: 90%;" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="editDeptDialog.form.data.code" style="width: 90%;" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="editDeptDialog.form.data.managerId" style="width: 90%;" @visible-change="editDeptDialog.methods.onVisibleChangeOfManager">
            <el-option
              v-for="v of editDeptDialog.ManagerList"
              :key="v.id"
              :label="v.username"
              :value="v.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="editDeptDialog.form.data.introduce" style="width: 90%;" type="textarea" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editDeptDialog.methods.ok">确定</el-button>
          <el-button @click="editDeptDialog.visible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getDepartments, delDepartment, getDepartmentId, putDepartment, getManagerList, postDepartment } from '@/api/department'
import { Message } from 'element-ui'

export default {
  name: 'Department',
  data() {
    return {
      isLoadingOfList: false,
      editDeptDialog: {
        title: '编辑部门',
        ManagerList: [],
        methods: Object.seal({
          onVisibleChangeOfManager: (visible) => {
            if (!visible) {
              this.$refs.refEditDeptForm.validateField('managerId')
            }
          },
          open: async(department) => {
            this.$refs.refEditDeptForm?.resetFields()
            this.editDeptDialog.ManagerList = await getManagerList()
            this.editDeptDialog.title = `添加【${department.name}】的子部门`
            this.editDeptDialog.form.data = await getDepartmentId(department.id)
            this.editDeptDialog.visible = true
          },
          ok: async() => {
            await this.$refs.refEditDeptForm.validate()
            console.log('验证通过')
            await putDepartment(this.editDeptDialog.form.data)
            Message.success('编辑部门成功')
            this.editDeptDialog.visible = false
            this.getDepartments()
          }
        }),
        visible: false,
        form: {
          data: {
            id: '',
            createTime: '',
            name: '',
            code: '',
            managerId: '',
            introduce: '',
            pid: '' // 父部门的id
          },
          rules: Object.seal({
            name: [
              { required: true, message: '部门名称不能为空' },
              { min: 2, max: 10, message: '部门名称的长度为2-10个字符' },
              {
                validator: async(rule, value, cb) => {
                  const departments = await getDepartments()
                  if (departments.filter(v => v.id !== this.editDeptDialog.form.data.id).some(v => v.name === value)) {
                    cb(new Error('部门中已有该名称'))
                  } else {
                    cb()
                  }
                },
                // 当失焦时触发
                trigger: 'blur'
              }
            ],
            code: [
              { required: true, message: '部门编码不能为空' },
              { min: 2, max: 10, message: '部门编码的长度为2-10个字符' },
              {
                validator: async(rule, value, cb) => {
                  const departments = await getDepartments()
                  if (departments.filter(v => v.id !== this.editDeptDialog.form.data.id).some(v => v.code === value)) {
                    cb(new Error('部门中已有该编码'))
                  } else {
                    cb()
                  }
                },
                // 当失焦时触发
                trigger: 'blur'
              }
            ],
            managerId: [{ required: true, message: '部门负责人不能为空' }],
            introduce: [
              { required: true, message: '部门介绍不能为空' },
              { min: 1, max: 100, message: '部门介绍的长度为1-100个字符' }
            ]
          })
        }
      },
      addDeptDialog: {
        title: '添加子部门',
        ManagerList: [],
        methods: Object.seal({
          onVisibleChangeOfManager: (visible) => {
            if (!visible) {
              this.$refs.refAddDeptForm.validateField('managerId')
            }
          },
          open: async(department) => {
            this.$refs.refAddDeptForm?.resetFields()
            this.addDeptDialog.ManagerList = await getManagerList()
            this.addDeptDialog.title = `添加【${department.name}】的子部门`
            this.addDeptDialog.form.data.pid = department.id
            this.addDeptDialog.visible = true
          },
          ok: async() => {
            const loading = this.$loading({
              target: this.$refs.refAddDeptForm.$el
            })
            await this.$refs.refAddDeptForm.validate()
            console.log('验证通过')
            await postDepartment(this.addDeptDialog.form.data)
            loading.close()
            Message.success('添加部门成功')
            this.addDeptDialog.visible = false
            this.getDepartments()
          }
        }),
        visible: false,
        form: {
          data: {
            name: '',
            code: '',
            managerId: '',
            introduce: '',
            pid: '' // 父部门的id
          },
          rules: Object.seal({
            name: [
              { required: true, message: '部门名称不能为空' },
              { min: 2, max: 10, message: '部门名称的长度为2-10个字符' },
              {
                validator: async(rule, value, cb) => {
                  const loading = this.$loading({
                    target: this.$refs.refAddDeptFormOfName.$el
                  })
                  const departments = await getDepartments()
                  loading.close()
                  if (departments.some(v => v.name === value)) {
                    cb(new Error('部门中已有该名称'))
                  } else {
                    cb()
                  }
                },
                // 当失焦时触发
                trigger: 'blur'
              }
            ],
            code: [
              { required: true, message: '部门编码不能为空' },
              { min: 2, max: 10, message: '部门编码的长度为2-10个字符' },
              {
                validator: async(rule, value, cb) => {
                  const loading = this.$loading({
                    target: this.$refs.refAddDeptFormOfName.$el
                  })
                  const departments = await getDepartments()
                  loading.close()
                  if (departments.some(v => v.code === value)) {
                    cb(new Error('部门中已有该编码'))
                  } else {
                    cb()
                  }
                },
                // 当失焦时触发
                trigger: 'blur'
              }
            ],
            managerId: [{ required: true, message: '部门负责人不能为空' }],
            introduce: [
              { required: true, message: '部门介绍不能为空' },
              { min: 1, max: 100, message: '部门介绍的长度为1-100个字符' }
            ]
          })
        }
      },
      list: [
        // {
        //   name: '传智教育',
        //   children: [
        //     { name: '总裁办' },
        //     { name: '行政部' },
        //     { name: '财务部' },
        //     {
        //       name: '人事部',
        //       children: [
        //         { name: '人事部1' },
        //         { name: '人事部2' },
        //         { name: '人事部3' }
        //       ]
        //     }

        //   ]
        // }
      ],
      treeProps: Object.seal({
        label: 'name', // 告诉 el-tree 组件 去数据源 取点对象中的 哪个数据 作为节点标题
        children: 'children' // 告诉 el-tree 组件 取数据源 节点对象中的 哪个属性 作为子节点
      })
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async handleCommand(e, data) {
      console.log(e, data)
      if (e === 'add') {
        this.addDeptDialog.methods.open(data)
      } else if (e === 'edit') {
        this.editDeptDialog.methods.open(data)
      } else if (e === 'del') {
        await this.$confirm(`您确定要删除${data.name}吗？`)
        await delDepartment(data.id)
        Message.success('删除成功')
        await this.getDepartments()
      }
    },
    async getDepartments() {
      const departments = await getDepartments()
      // 根据 pid 找儿子们
      function getChildren(pid) {
        return departments.filter(v => v.pid === pid)
      }

      // 循环每一个对象，都给他找一遍儿子
      departments.forEach(v => {
        v.children = getChildren(v.id)
      })

      // 将一级节点找出来，就是 pid === 0 的
      this.list = departments.filter(v => v.pid === 0)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}

</style>
